package com.hotcode;

/**
 * @Author: huangzhigao
 * @Date: 2023/2/25 10:18
 */
public class leecode5 {
    public String longestPalindrome(String s) {
        if (s.length() < 2) {
            return s;
        }

        String res = "";
        for (int i = 0; i < s.length(); i++) {
            String p1 = findPalindrome(s, i, i);
            String p2 = findPalindrome(s, i, i + 1);
            res = p1.length() > res.length() ? p1 : res;
            res = p2.length() > res.length() ? p2 : res;
        }
        return res;

    }

    public String findPalindrome(String s, int left, int right) {
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        }
        return s.substring(left + 1, right);
    }

    public String longestPalindrome2(String s) {
        if (s.length() == 0) {
            return "";
        }

        int maxStart = 0;
        int maxEnd = 0;
        int maxLength = 1;
        boolean[][] dp = new boolean[s.length()][s.length()];
        for (int right = 1; right < s.length(); right++) {
            for (int left = 0; left < right; left++) {
                if (s.charAt(left) == s.charAt(right) && (right - left <= 2 || dp[left + 1][right - 1])) {
                    if (right - left + 1 > maxLength) {
                        maxStart = left;
                        maxEnd = right;
                        maxLength = right - left + 1;
                    }
                }
            }
        }


        return s.substring(maxStart, maxEnd+1);

    }
}
